package com.example.forum.exception;
import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
//处理全局异常的类
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler  {
    @ResponseBody
    @ExceptionHandler(ApplicationException.class)
    public AppResult applicationExceptionHandler(ApplicationException e){
        //打印异常信息
//        e.printStackTrace();  //上生产环境之前删除
        log.error(e.getMessage());
        //如果发生了异常 返回异常
        if(e.getErrorResult()!=null){
            return e.getErrorResult();
        }
        if(e.getMessage()==null||e.getMessage().equals("")){
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
        //返回具体错误信息
        return AppResult.failed(e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public AppResult exceptionHandler(Exception e){
        //打印异常信息
//        e.printStackTrace();  //上生产环境之前删除
        log.error(e.getMessage());
        if(e.getMessage()==null||e.getMessage().equals("")){
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
        //返回异常信息
        return AppResult.failed(e.getMessage());
    }

}
